<?php

declare(strict_types=1);

namespace App\Service;

use App\Constants\ErrorCode;
use App\Exception\BusinessException;
use App\Library\Common;
use App\Model\FlyCoupon;
use App\Model\FlyCouponUser;

/**
 * 订单优惠券处理
 * Class OrderCouponService
 * @package App\Service
 */
class OrderCouponService extends BaseService
{

    /**
     * 验证订单商品并计算优惠金额
     * @param int $user_id
     * @param int $user_coupon_id
     * @param int $shop_id
     * @param array $products
     * @return array
     */
    public function verifyOrderCoupon(int $user_id, int $user_coupon_id, int $shop_id, array $products): array
    {
        $instance = make(FlyCouponUser::class)
            ->with(['with_coupon'])
            ->has('with_coupon')
            ->where(['user_id' => $user_id, 'id' => $user_coupon_id, 'is_used' => 0, 'shop_id' => $shop_id])
            ->first();
        $my_coupon = empty($instance) ? [] : $instance->toArray();
        // 优惠券无效
        $can_use = 1;
        $coupon_field_total = 0;
        if (empty($my_coupon) || ($my_coupon['with_coupon']['use_type'] == FlyCouponService::USE_TYPE_PRODUCT && empty($my_coupon['with_coupon']['link_product']))) {
            $can_use = 0;
            goto ret;
        }

        $coupon_p = array_column($my_coupon['with_coupon']['link_product'], 'product_id');
        // 是否所有商品可用
        $all_can_use = $my_coupon['with_coupon']['use_type'] == FlyCouponService::USE_TYPE_SHOP ? 1 : 0;

        foreach ($products as $product) {
            // 不限商品 或 指定商品 ：计算优惠满**金额
            if ($all_can_use == 1 || in_array($product['product_id'], $coupon_p)) {
                $coupon_field_total += Common::yuan2fen(floatval($product['single_price'])) * $product['quantity'];
            }
        }
        ret:
        $res = [
            'can_use' => empty($coupon_field_total) ? 0 : $can_use,
            'coupon' => $my_coupon,
            'coupon_price' => 0
        ];
        if ($res['can_use'] && $coupon_field_total >= Common::yuan2fen(floatval($my_coupon['with_coupon']['min_limit']))) {
            $res['coupon_price'] = Common::yuan2fen(floatval($my_coupon['with_coupon']['price']));
        }
        return $res;
    }

    /**
     * 返还用户订单所使用的优惠券
     * @param int $userId
     * @param int $userCouponId
     * @return bool
     */
    public function backUserCoupon(int $userId, int $userCouponId): bool
    {
        $user_coupon_record = make(FlyCouponUser::class)
            ->where('id', '=', $userCouponId)
            ->where('user_id', '=', $userId)
            ->where('is_use', '=', 1)
            ->first();
        if (empty($user_coupon_record)) {
            return false;
        }
        $user_coupon_record->is_used = 0; // 修改为未使用状态
        $user_coupon_record->use_time = 0;
        $user_coupon_record->order_id = 0;
        if (!$user_coupon_record->save()) {
            return false;
        }
        return true;
    }

    /**
     * 订单适用优惠券：修改优惠券状态
     * @param int $userId
     * @param int $userCouponId
     * @param int $orderID
     * @return bool
     */
    public function useUserCoupon(int $userId, int $userCouponId, int $orderID): bool
    {
        $user_coupon_record = make(FlyCouponUser::class)
            ->where('id', '=', $userCouponId)
            ->where('user_id', '=', $userId)
            ->where('is_use', '=', 1)
            ->first();
        if (empty($user_coupon_record)) {
            return false;
        }
        $user_coupon_record->is_used = 1; // 修改为未使用状态
        $user_coupon_record->use_time = time();
        $user_coupon_record->order_id = $orderID;
        if (!$user_coupon_record->save()) {
            return false;
        }
        return true;
    }

}